package chapter30;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.net.*;
import java.io.*;
import java.util.ArrayList;

public class WebBrowser extends JFrame {
    
    private JTabbedPane pane;
    private ArrayList<JEditorPane> editors;
    private JTextField urlField;
    
    public WebBrowser() {
        pane = new JTabbedPane();
        editors = new ArrayList<JEditorPane>();
        
        for (int i = 0; i < 5; i++) {
            JEditorPane editor = new JEditorPane();
            editors.add(editor);
            editor.setEditable(false);
            editor.addHyperlinkListener(new editorListener());
            JScrollPane viewer = new JScrollPane();
            viewer.getViewport().add(editor, null);
            pane.addTab("Untitled", viewer);
        }
        
        urlField = new JTextField();
        JPanel url = new JPanel();
        url.setLayout(new BorderLayout());
        url.add(new JLabel("URL"), BorderLayout.WEST);
        url.add(urlField, BorderLayout.CENTER);
        
        add(url, BorderLayout.NORTH);
        add(pane, BorderLayout.CENTER);
        
        urlField.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                
                try {
                    URL url = new URL(urlField.getText().trim());
                    
                    JEditorPane editor =
                        (JEditorPane) ((JScrollPane) pane.getSelectedComponent())
                        .getViewport().getView();
                    
                    editor.setPage(url);
                    pane.setTitleAt(pane.getSelectedIndex(), url.getHost());
                }
                catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }
    
    private class editorListener implements HyperlinkListener {
        
        @Override
        public void hyperlinkUpdate(HyperlinkEvent he) {
            try {
                if (he.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                    ((JEditorPane) ((JScrollPane) pane.getSelectedComponent())
                        .getViewport().getView()).setPage(he.getURL());
                }
            }
            catch (IOException ioex) {
                ioex.printStackTrace();
            }
            catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    
    public static void main(String[] args) {
        JFrame browser = new WebBrowser();
        browser.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        browser.setTitle("Web Browser");
        browser.setSize(800, 600);
        browser.setVisible(true);
        
    }
}
